//
//  AccountsViewController.m
//  iMoney
//
//  Created by Sean McGrail on 2/2/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "AccountsViewController.h"
#import "Account.h"
#import "ExpenseViewController.h"
#import "AccountCell.h"
#import "TransferView.h"
#import "AccountAddView.h"

@implementation AccountsViewController


- (id)init
{
	if (self = [super init]) 
	{
		
		self.tabBarItem.image = [UIImage imageNamed:@"dollar.png"];
		self.title = @"Accounts";
	}
	
	
	return self;
}


- (void)loadView {
	
	CGRect frame = [[UIScreen mainScreen] applicationFrame];	
	self.view= [[[UIView alloc] initWithFrame:frame] autorelease];
	self.view.autoresizesSubviews = YES;
	
	tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height-90) style: UITableViewStyleGrouped];
	
	//self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
	tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
	tableView.rowHeight = 60;
	tableView.backgroundColor = [UIColor clearColor];
	
	tableView.dataSource = self;
	tableView.delegate = self;
	
	tableView.autoresizesSubviews= YES;
	
	
		//UIView *containerView =
//		[[[UIView alloc]
//		  initWithFrame:CGRectMake(0, 0, 300, 60)]
//		 autorelease];
//		UILabel *headerLabel =
//		[[[UILabel alloc]
//		  initWithFrame:CGRectMake(frame.size.width/2 - 50, 20, 150, 40)]
//		 autorelease];
//		//headerLabel.text = NSLocalizedString(@"Accounts", @"");
//		headerLabel.text = [NSString stringWithFormat:@"%0.2f", [[iMoneyAppDelegate getMoneyState] getTotalAccountsAmount]];
//		headerLabel.textColor = [UIColor whiteColor];
//		headerLabel.shadowColor = [UIColor blackColor];
//		headerLabel.shadowOffset = CGSizeMake(0, 1);
//		headerLabel.font = [UIFont boldSystemFontOfSize:18];
//		headerLabel.backgroundColor = [UIColor clearColor];
//		[containerView addSubview:headerLabel];
//		
//		
//		tableView.tableHeaderView = containerView;
	
	
    doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneEditing:)];

	
	[self.view addSubview:tableView];
	
	UIImageView* background = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"gradientBackground.png"]];
	[self.view addSubview:background];
	[self.view sendSubviewToBack:background];
	[background release];
}

- (void)viewDidLoad {
	

	UIBarButtonItem *options = [[[UIBarButtonItem alloc]
								 initWithTitle:@"Options" 
								 style:UIBarButtonItemStylePlain
								 target:self action:@selector(options:)] autorelease];
	
	
	
	self.navigationItem.leftBarButtonItem = options;
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	
	[tableView reloadData];
}

/*
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 }
 */
/*
 - (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
 }
 */
/*
 - (void)viewDidDisappear:(BOOL)animated {
 [super viewDidDisappear:animated];
 }
 */



#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return  [[iMoneyAppDelegate getMoneyState] numAccounts];
}


- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	const NSInteger TOP_LABEL_TAG = 1001;
	const NSInteger BOTTOM_LABEL_TAG = 1002;
    static NSString *CellIdentifier = @"AccountCell";
    
	UILabel* topLabel;
	UILabel* bottomLabel;
	
	//AccountCell *cell = (AccountCell *)[aTableView dequeueReusableCellWithIdentifier:CellIdentifier];	
	//	if (cell == nil) {
	//		cell = [[[AccountCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; // changed this
	//		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	//	}
	
	
    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
		
		const CGFloat LABEL_HEIGHT = 20;
		
		topLabel =
		[[[UILabel alloc]
		  initWithFrame:
		  CGRectMake(
					 2.0 * cell.indentationWidth,
					 0.5 * (aTableView.rowHeight - 2 * LABEL_HEIGHT),
					 aTableView.bounds.size.width -
					 4.0 * cell.indentationWidth,
					 LABEL_HEIGHT)]
		 autorelease];
		[cell.contentView addSubview:topLabel];
		
		//
		// Configure the properties for the text that are the same on every row
		//
		topLabel.tag = TOP_LABEL_TAG;
		topLabel.backgroundColor = [UIColor clearColor];
		topLabel.textColor = [UIColor colorWithRed:0.25 green:0.0 blue:0.0 alpha:1.0];
		topLabel.highlightedTextColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0];
		topLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize]];
		
		//
		// Create the label for the top row of text
		//
		bottomLabel =
		[[[UILabel alloc]
		  initWithFrame:
		  CGRectMake(
					 2.0 * cell.indentationWidth + 180,
					 0.5 * (aTableView.rowHeight - 2 * LABEL_HEIGHT),
					 aTableView.bounds.size.width -
					 4.0 * cell.indentationWidth,
					 LABEL_HEIGHT)]
		 autorelease];
		[cell.contentView addSubview:bottomLabel];
		
		//
		// Configure the properties for the text that are the same on every row
		//
		bottomLabel.tag = BOTTOM_LABEL_TAG;
		bottomLabel.backgroundColor = [UIColor clearColor];
		bottomLabel.textColor = [UIColor colorWithRed:0.25 green:0.0 blue:0.0 alpha:1.0];
		bottomLabel.highlightedTextColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0];
		bottomLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize] - 2];
    }
	else
	{
		topLabel = (UILabel *)[cell viewWithTag:TOP_LABEL_TAG];
		bottomLabel = (UILabel *)[cell viewWithTag:BOTTOM_LABEL_TAG];
	}
	
	
	//get account and set values
	Account* a = [[iMoneyAppDelegate getMoneyState] getAccount:indexPath.row];
	
	topLabel.text =  [a accountName];
	
	double totalAmount = [a totalAmount];
	if(totalAmount <0)
	{
		bottomLabel.textColor = [UIColor redColor];
	}
	else if(totalAmount == 0)
	{
		bottomLabel.textColor = [UIColor blackColor];
	}
	else
		bottomLabel.textColor = [UIColor blueColor];
	
	bottomLabel.text = [NSString stringWithFormat:@"%.2f", totalAmount];
	
	//cell.textLabel.text = a.accountName;
	
	//[cell setVals:[a accountName] : [a totalAmount]];
	
	UIImage *rowBackground;
	//UIImage *selectionBackground;
	NSInteger sectionRows = [aTableView numberOfRowsInSection:[indexPath section]];
	NSInteger row = [indexPath row];
	if (row == 0 && row == sectionRows - 1)
	{
		rowBackground = [UIImage imageNamed:@"topAndBottomRow.png"];
		//selectionBackground = [UIImage imageNamed:@"topAndBottomRowSelected.png"];
	}
	else if (row == 0)
	{
		rowBackground = [UIImage imageNamed:@"topRow.png"];
		//selectionBackground = [UIImage imageNamed:@"topRowSelected.png"];
	}
	else if (row == sectionRows - 1)
	{
		rowBackground = [UIImage imageNamed:@"bottomRow.png"];
		//selectionBackground = [UIImage imageNamed:@"bottomRowSelected.png"];
	}
	else
	{
		rowBackground = [UIImage imageNamed:@"middleRow.png"];
		//selectionBackground = [UIImage imageNamed:@"middleRowSelected.png"];
	}
	
	UIImageView* backg = [[UIImageView alloc] initWithImage:rowBackground];
	
	//((UIImageView *)cell.backgroundView).image = rowBackground;
	[cell setBackgroundView:backg];
	[cell sendSubviewToBack:backg];
	[backg release];
	
	
    // Set up the cell
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic -- create and push a new view controller
	
	ExpenseViewController* evc = [[ExpenseViewController alloc] initWithAccount:[[iMoneyAppDelegate getMoneyState] getAccount:indexPath.row]];
	evc.title = [[[iMoneyAppDelegate getMoneyState] getAccount:indexPath.row] accountName];
	
	[[self navigationController] pushViewController:evc animated:YES];
	[evc release];
	
}


- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return UITableViewCellEditingStyleDelete;
}


- (void)tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
		
		//TODO remove account from model 
		
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Remove" message:@"Are you sure you want to delete this account?."  delegate:self cancelButtonTitle:@"NO" otherButtonTitles: @"Yes", nil];
		[alert show];
		[alert release];
		
		removeAcc = indexPath.row;
		
		
		// Delete the row from the data source
        //[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
		
    }
}


- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
	
	[super setEditing:editing animated:animated];
	[tableView reloadData];
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if(removeAcc >= 0)
	{
		[[iMoneyAppDelegate getMoneyState] removeAccountIndex:removeAcc];
		[tableView reloadData];
	}
	
}

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */


/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */



//---------------------------action stuff


//Handle the options
-(void) options:(id)sender
{
	
	// open a dialog options
	UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Options"
															 delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil
													otherButtonTitles:@"Transfer Amount", @"Add Account",@"Remove Account",@"Save to File", nil];
	
	//[actionSheet dismissWithClickedButtonIndex:2 animated:YES];
	
	actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
	[actionSheet showInView:self.view]; // show from our table view (pops up in the middle of the table)
	[actionSheet release];
	
	
}


-(void)doneEditing:(id)sender
{
	self.navigationItem.rightBarButtonItem= NULL;
	[tableView setEditing:NO animated:YES];	
}


- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{

	//dont do this for a remove
	if(buttonIndex !=2 && buttonIndex !=3 && buttonIndex !=4){
	[((iMoneyAppDelegate*)[[UIApplication sharedApplication] delegate]) toggleTabBar];
	[((iMoneyAppDelegate*)[[UIApplication sharedApplication] delegate]) toggleNavBar];
	}
		
	switch(buttonIndex)
	{
		case 0:	//transfer
			
		{
			TransferView* transferView = [[TransferView alloc] initWithFrame:CGRectMake(5, 3, 310, 440)];
			
			[self.view addSubview:transferView];
			[self.view bringSubviewToFront:transferView];
			
			[transferView release];
			
			break;
		}
			
		case 1:  //add account
		{
			
			
			AccountAddView *addView = [[AccountAddView alloc] initWithFrameAndTable:CGRectMake(5, 3, 310, 440): tableView];
			
			CATransition *applicationLoadViewIn = [CATransition animation];
			[applicationLoadViewIn setDuration:.5];
			[applicationLoadViewIn setType:kCATransitionReveal];
			[applicationLoadViewIn setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]];
			[[addView layer] addAnimation:applicationLoadViewIn forKey:kCATransitionReveal];
			
			
			[self.view addSubview:addView];
			[self.view bringSubviewToFront:addView];
			
			[addView release];
			
			break;
		}
			
		case 2: //remove accounts
		{
			self.navigationItem.rightBarButtonItem= doneButton;
			[tableView setEditing:YES animated:YES];
			break; 
		}
		case 3:
		{
			if([[iMoneyAppDelegate getMoneyState] saveDataFile:[iMoneyAppDelegate getFilePath]] == YES)
			{
				UIAlertView *myAlertView = [[UIAlertView alloc] 
											initWithTitle:@"File Saved" message:@""
											delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];	
				
				[myAlertView show];
				[myAlertView release];
			}
			else 
			{
				UIAlertView *myAlertView = [[UIAlertView alloc] 
											initWithTitle:@"Could not save file" message:@""
											delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];	
				
				[myAlertView show];
				[myAlertView release];
			}

			break;	
			
			
			
		}
		case 4: //cancel
		{
			break;
		}	
			
	}	
	
	
}





//---------------


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
}

- (void)dealloc {
	
	[doneButton release];
	[tableView release];
    [super dealloc];
}


@end

